package web

import (
	"encoding/json"
	logv1 "gitee.com/xiao_hange/go-admin-api/api/proto/gen/log/v1"
	"gitee.com/xiao_hange/go-admin-pkg/pkg/logger"
	"github.com/gin-gonic/gin"
	"go-admin/server/internal/domain"
	"go-admin/server/internal/web/form"
	"go-admin/server/internal/web/vo"
	"go.opentelemetry.io/otel"
	"go.opentelemetry.io/otel/trace"
	"google.golang.org/grpc/status"
	"net/http"
)

var (
	_ handler = &LogHandler{}
)

type LogHandler struct {
	svc    logv1.LogServiceClient
	l      logger.AppLogger
	tracer trace.Tracer
}

func NewLogHandler(svc logv1.LogServiceClient, l logger.AppLogger) *LogHandler {
	return &LogHandler{
		svc:    svc,
		l:      l,
		tracer: otel.GetTracerProvider().Tracer("LOG web层"),
	}
}

func (f *LogHandler) RegisterRoutes(server *gin.Engine) {
	fg := server.Group("/log")

	fg.GET("/log-lst", f.logLst)
}

func (f *LogHandler) logLst(ctx *gin.Context) {
	var req form.LogLstReq
	err := ctx.Bind(&req)
	if err != nil {
		return
	}
	index := domain.GormLogIndex
	Resp, err := f.svc.SearchLog(ctx.Request.Context(), &logv1.SearchLogRequest{
		Index: domain.GormLogIndex,
		Page:  req.Page,
		Limit: req.Limit,
	})
	if err != nil {
		s, _ := status.FromError(err)
		RenderJSON(ctx, http.StatusOK, http.StatusOK, "内部错误！"+s.Message(), nil)
		return
	}
	switch index {
	case domain.GormLogIndex:
		res := toData[vo.GormInfo](Resp.Data)
		RenderJSONPage(ctx, http.StatusOK, http.StatusOK, "ok！", res, Resp.Nt)
	}
	return
}

func toData[T any](datas []*logv1.Data) []T {
	var res []T
	for _, d := range datas {
		var data T
		_ = json.Unmarshal([]byte(d.Message), &data)
		res = append(res, data)
	}
	return res
}
